﻿namespace EFS.RC.CC.Tools.Deployment.Remove
{
	/// <summary>
	/// Agent decomission
	/// </summary>
	internal class Agent : EFS.Common.Async.AsyncRoot
	{
		#region Composition

		// sync access
		private object syncAccess = new object();

		// agent id 
		private System.Int32 agentID;
		
		/// <summary>
		/// Status
		/// </summary>
		public enum RemoveStatus { Idle, Executed }

		// Status
		private RemoveStatus status = RemoveStatus.Idle;

		#endregion

		#region Constructor
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="conversation"></param>
		/// <param name="remoteEndpoint"></param>
		public Agent(System.Int32 agentID)
		{
			// set
			this.agentID = agentID;

			// log
			EFS.EventLog.Log.LogInfo("Agent", this);
		}

		#endregion

		#region Usage

		/// <summary>
		/// Describe this object into a nice formated string
		/// </summary>
		/// <returns></returns>
		public override System.String Describe()
		{
			return System.String.Format("EFS.RC.CC.Tools.Deployment.Remove.Agent AgentID: {0}", agentID);
		}

		/// <summary>
		/// Execute
		/// </summary>
		public EFS.Common.Async.AsyncProcess Execute()
		{
			// log
			EFS.EventLog.Log.LogInfo("Execute", this);

			// start
			return BeginAsyncProcess2(ExecuteRemove, OnExecuteRemoveComplete);
		}

		#endregion

		#region Runtime

		/// <summary>
		/// Unhandled exception
		/// </summary>
		/// <param name="ex"></param>
		protected override void OnException(System.Exception ex)
		{
			// check
			EFS.Common.Verify.Reference(ex, "ex");

			// log
			EFS.EventLog.Log.LogException(ex, this);

			// SAL
			EFS.RC.CC.Tools.Loggers.SAL.Add(null, "OnException", ex, this);

		}

		#endregion

		#region Execute

		/// <summary>
		/// ExecuteRemove
		/// </summary>
		private void ExecuteRemove()
		{
			// log
			EFS.EventLog.Log.LogInfo("ExecuteRemove", this);

			// sync access
			// ~ commented for performance ~  EFS.EventLog.Log.LogExtended("Entering lock", new System.Diagnostics.StackTrace());
			lock (syncAccess)
			{
				if (status != RemoveStatus.Idle)
				{
					throw new System.InvalidOperationException("Only Idle Remove can be started");
				}

				// started
				status = RemoveStatus.Executed;
			}

			// delete
			EFS.RC.CC.Deployment.Tables.Tools.Agents.DeleteWithRelations(agentID);
		}

		/// <summary>
		/// ExecuteRemove complete
		/// </summary>
		/// <param name="ar"></param>
		private void OnExecuteRemoveComplete(EFS.Common.Async.AsyncProcess ap)
		{
			// log
			EFS.EventLog.Log.LogInfo("OnExecuteRemoveComplete", this);

			try
			{
				// check
				ap.Throw();

				// log
				EFS.EventLog.Log.LogInfo("OnExecuteRemoveComplete SUCCCESS", this);
			}
			catch (System.Exception ex)
			{
				// log
				EFS.EventLog.Log.LogException(ex, this);
			}
		}

		#endregion
	}
}
